package com.hengxinyongli.iam.remote;

import com.alibaba.dubbo.config.annotation.Service;
import com.google.common.collect.Lists;
import com.hengxinyongli.iam.dto.Subject;
import com.hengxinyongli.iam.entity.Department;
import com.hengxinyongli.iam.entity.User;
import com.hengxinyongli.iam.service.DepartmentService;
import com.hengxinyongli.iam.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.LinkedList;
import java.util.List;

@Service
public class IamManageServiceImpl implements IamManageService {

    private Logger logger = LoggerFactory.getLogger(IamManageServiceImpl.class);

    @Autowired
    DepartmentService departmentService;
    @Autowired
    UserService userService;

    @Override
    public List<Subject> getSubjectByDepartType(String label, Boolean fetchAll) {
        logger.info("getSubjectByDepartType code={}, fetchAll={}",label,fetchAll);
        LinkedList<Subject> subjects = Lists.newLinkedList();
        if(!fetchAll){
            List<User> users = userService.fetchUserInfoByDepCode(label);
            if(!users.isEmpty()){
                 subjects = userToSubject(users);
            }
        }else{
            List<Department> departments = departmentService.fetchDepartInfo(label, fetchAll);
            if(departments.isEmpty()){
                logger.info("getSubjectByDepartType departments isEmpty...");
                return subjects;
            }
            for (Department dep : departments) {
                List<User> users = userService.fetchUserInfoByDepCode(dep.getCode());
                if(!users.isEmpty()){
                    LinkedList<Subject> toSubjects = userToSubject(users);
                    subjects.addAll(toSubjects);
                }
            }
        }
        logger.info("getSubjectByDepartType result= {}",subjects);
        return subjects;
    }

    private LinkedList<Subject> userToSubject(List<User> users) {
        LinkedList<Subject> linkedList = Lists.newLinkedList();
        users.forEach( u ->{
            Subject subject = new Subject();
            subject.setUserId(u.getId());
            subject.setUserName(u.getUserName());
            subject.setMobile(u.getMobile());
            subject.setUserType(u.getUserType());
            subject.setDepId(u.getDepId());
            subject.setDepLabel(u.getDepCode());
            linkedList.add(subject);
        });
        return linkedList;
    }
}
